﻿using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using RG.Common.Export;

namespace RG.Common.WPF.Controls.ColumnInfoDataGrid
{
    public class ColumnInfoSortDescription
    {
        public IColumnInfo Column { get; private set; }
        public ListSortDirection Direction { get; set; }

        public ColumnInfoSortDescription(IColumnInfo column)
        {
            Column = column;
            Direction = ListSortDirection.Ascending;
        }
    }

    public class ColumnInfoSort : IComparer
    {
        public ColumnInfoSort(IEnumerable<ColumnInfoSortDescription> sortDescriptions)
        {
            SortDescriptions = sortDescriptions;
        }

        public IEnumerable<ColumnInfoSortDescription> SortDescriptions { get; private set; }

        public int Compare(object x, object y)
        {
            foreach (var sort in SortDescriptions)
            {
                var s1 = sort.Column.GetValueForCompare(x);
                var s2 = sort.Column.GetValueForCompare(y);

                if (s1 == null && s2 == null) return 0; // если оба null
                if (s1 == null) return sort.Direction == ListSortDirection.Ascending ? -1 : 1; // если только s1 = null
                
                var cmp = s1.CompareTo(s2);
                if (cmp != 0)
                    return sort.Direction == ListSortDirection.Ascending ? cmp : -cmp;
            }
            return 0;
        }
    }
}
